﻿using PerpheralDevice.Units;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PerpheralDevice.LeadShine
{
    /// <summary>
    /// 雷赛DMC板卡 输出开关(应用读写开关)
    /// </summary>
    public class DMCSwitchRW : SwitchRW {

        private ushort mfCardNO;
        private ushort mfMacAddr;
        public override string UnitID { get; }
        public DMCSwitchRW(PerpDev perpDev, int macAddr) {
            this.PerpDev = perpDev;
            this.UnitID = macAddr.ToString();

            this.TestIndex = Interlocked.Increment(ref PerpDevUnit.mfTestIndex);
        }
        
        public override SwitchRW View() {

            if (this.PerpDev.IsMocking) {
                this.MockView();
                return this;
            }

            uint tempDoState = LTDMC.dmc_read_outport(this.mfCardNO, 0);
            // 低电平有效
            bool tempIsOpen = (tempDoState & (1 << this.mfMacAddr)) == 0;
            if (tempIsOpen != this.IsOpen) {
                this.IsOpen = tempIsOpen;
                this.OnStatusChangedRaise();
            }

            return this;
        }

        public override SwitchRW Open() {
            AppFramework.Logger.ILogger.Default.Info($"{this.GetType().FullName}:{this.PerpDev.PerpDevName}=>{nameof(Open)}({this.TestIndex})");

            if (this.PerpDev.IsMocking) {
                this.MockOpen();
                return this;
            }

            // 低电平有效
            LTDMC.dmc_write_outbit(this.mfCardNO, this.mfMacAddr, 0);
            return this;
        }

        public override SwitchRW Shut() {
            AppFramework.Logger.ILogger.Default.Info($"{this.GetType().FullName}:{this.PerpDev.PerpDevName}=>{nameof(Shut)}({this.TestIndex})");
            if (this.PerpDev.IsMocking) {
                this.MockShut();
                return this;
            }

            // 低电平有效
            LeadShine.LTDMC.dmc_write_outbit(this.mfCardNO, this.mfMacAddr, 1);
            return this;
        }

    }
}
